<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { addEnterpriseRentAPI, delEnterpriseAPI, getEnterpriseListAPI, getEnterpriseRentAPI, getMyBuildingAPI } from '@/apis/park';
import router from '@/router';
import type { EnterpriseList, GetEnterpriseListParams, MyBuilding, POSTParkEnterpriseRentParams, Rents, Row } from '@/types/park';
import { ElMessage, ElMessageBox, type FormInstance, type UploadRequestOptions, type UploadUserFile } from 'element-plus';

import { ref, watch} from 'vue';
//获取企业列表的参数
const EnterpriseParams = ref<GetEnterpriseListParams>({
  page: 1,
  pageSize: 5,
  name: undefined
})
//获取企业列表
const getEnterpriseList = async () => {
  const res = await getEnterpriseListAPI(EnterpriseParams.value)
  enterpriseList.value=res.data.rows
  total.value=res.data.total
}
getEnterpriseList()
//企业信息列表
interface Row_ extends Row{
  rentList?:Rents[]
} 
const enterpriseList = ref<Row_[]>([])
//企业信息总数
const total = ref(0)
//删除企业
const delEnterprise = (id: string) => {

ElMessageBox.confirm('此操作将永久删除该企业, 是否继续?', '提示', {
  confirmButtonText: '确定',
  cancelButtonText: '取消',
  type: 'warning',
}).then(async()=>{
  try{
  await delEnterpriseAPI(id)
  getEnterpriseList()
  ElMessage.success('删除成功')
}catch(err:any){
  ElMessage.error(err.response.data.msg)
}
}).catch(() => { })
}
//控制合同弹窗
const showDialog=ref(false)
//添加合同
const addContract=(id:number)=>{
  showDialog.value=true
  rentForm.value.enterpriseId=id
}
const InfoForm=()=>{
 return { buildingId:undefined,
  contractId:undefined,
  contractUrl:'',
  endTime:'',
  enterpriseId:0,
  startTime:'',
  type:0}
}
// 初始化租赁表单数据
const rentForm = ref<POSTParkEnterpriseRentParams>(InfoForm())

// 表单验证规则
const rules = {
  buildingId: [
    { required: true, message: '请选择租赁楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁起止日期', trigger: 'change' }
  ],
  contractId: [
    { required: true, message: '请上传合同文件' }
  ]
}
//获取可租赁楼宇
const MyBuilding=ref<MyBuilding[]>()
const getMyBuilding=async()=>{
  const res=await getMyBuildingAPI()
  MyBuilding.value=res.data
}
getMyBuilding()
//添加合同表单
const addFormRef=ref<FormInstance>()
//上传文件
const UploadFile=async(options:UploadRequestOptions)=>{
  const fd=new FormData()
  fd.append('file',options.file)
  fd.append('type','contract')
const res=await uploadAPI(fd)
rentForm.value.contractId=res.data.id
rentForm.value.contractUrl=res.data.url
addFormRef.value?.validateField('contractId')
return res.data
}
//删除文件
const delFile=()=>{
  rentForm.value.contractId=undefined
  rentForm.value.contractUrl=''
  addFormRef.value?.validateField('contractId')
}
//文件列表
const fileList=ref<UploadUserFile[]>()
//添加合同确定
const addEnterPriseContract=async()=>{
  console.log(rentForm.value);
  await addFormRef.value?.validate()
  await addEnterpriseRentAPI(rentForm.value)
  addFormRef.value?.resetFields()
  RentTime.value=[]
  fileList.value=[]
  rentForm.value=InfoForm()
  ElMessage.success('添加成功')
  showDialog.value=false
}
//租赁日期
const RentTime=ref<string[]>([])
watch(RentTime,(val)=>{
if(val){
  console.log(val);
  
  rentForm.value.startTime=val[0]
  rentForm.value.endTime=val[1]
}else{
  rentForm.value.startTime=''
  rentForm.value.endTime=''
}
},{deep:true})
//取消添加合同
const cancleAdd=()=>{
  addFormRef.value?.resetFields()
  RentTime.value=[]
  fileList.value=[]
  rentForm.value=InfoForm()
  showDialog.value=false
}
//合同列表
const EnterPriseRents=ref<Rents[]>([])
//获取合同列表
const getRents=async(row:Row_)=>{
const res= await getEnterpriseRentAPI(row.id)
console.log(res.data);
row.rentList=res.data
}
</script>
<template>
  <div>
    <div class="building-container">
      <!-- 搜索区域 -->
      <div class="search-container">
        <div class="search-label">企业名称：</div>
        <el-input clearable placeholder="请输入内容" class="search-main" v-model="EnterpriseParams.name" />
        <el-button type="primary" @click="getEnterpriseList">查询</el-button>
      </div>
      <div class="create-container">
        <el-button type="primary" @click="router.push('/addenterprise')">添加企业</el-button>
      </div>
      <!-- 表格区域 -->
      <div class="table">
        <el-table style="width: 100%" :data="enterpriseList" @expand-change="getRents" row-key="id">
          <el-table-column type="expand">
    <template #default="{row}">
      <el-table :data="row.rentList">
        <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
        <el-table-column label="租赁起始时间" prop="startTime" />
        <el-table-column label="合同状态">
          <template #default="{row}">
            <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-else-if="row.status === 2" type="info">已到期</el-tag>
                  <el-tag v-else-if="row.status === 3" type="danger">已退租</el-tag>
          </template>
          </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default>
            <el-button type="success" link>续租</el-button>
            <el-button type="success" link>退租</el-button>
            <el-button type="success" link>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </el-table-column>
          <el-table-column type="index" label="序号" width="120" />
          <el-table-column label="企业名称" width="320" prop="name" />
          <el-table-column label="联系人" prop="contact" />
          <el-table-column label="联系电话" prop="contactNumber" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button size="small" type='primary' link @click="addContract(row.id)">添加合同</el-button>
              <el-button size="small" type='primary' link>查看</el-button>
              <el-button size="small" type='primary' link @click="router.push(`/addenterprise/${row.id}`)">编辑</el-button>
              <el-button size="small" type='primary' link @click="delEnterprise(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-container">
        <el-pagination :total="total" :page-sizes="[2, 5, 10, 20]" 
        layout="total,sizes, prev, pager, next,jumper" 
        v-model:page-size="EnterpriseParams.pageSize" v-model:current-page="EnterpriseParams.page" 
        @change="getEnterpriseList" @size-change="EnterpriseParams.page=1" />
      </div>
    </div>
    <el-dialog v-model="showDialog" width="580" title="添加合同" :close-on-click-modal="false">
      <div class="form-container">
        <el-form 
          ref="addFormRef" 
          :model="rentForm" 
          :rules="rules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option v-for="item in MyBuilding" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="endTime">
            <el-date-picker v-model="RentTime" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload accept=".doc, .pdf"
            :on-remove="delFile"
            :limit="1"
            :http-request="UploadFile"
            v-model:file-list="fileList"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <template #tip>
                <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="cancleAdd">取消</el-button>
        <el-button type="primary" @click="addEnterPriseContract">确定</el-button>
      </template>
    </el-dialog>
  

  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>